<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button
            class="addbtn"
            @click="addDialogVisible = true"
            type="primary"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-row>
        <el-table :data="rolesList" stripe border style="width: 100%">
          <!-- 展开列 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
                v-for="(value1, index1) in scope.row.children"
                :key="value1.id"
              >
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag
                    closable
                    @close="deleteRights(scope.row, value1.id)"
                    >{{ value1.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级权限 -->
                <el-col :span="19">
                  <el-row
                    :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                    v-for="(value2, index2) in value1.children"
                    :key="value2.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        closable
                        @close="deleteRights(scope.row, value2.id)"
                        type="success"
                        >{{ value2.authName }}</el-tag
                      >
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 渲染三级权限 -->
                    <el-col :span="18">
                      <el-tag
                        closable
                        @close="deleteRights(scope.row, value3.id)"
                        v-for="value3 in value2.children"
                        :key="value3.id"
                        type="warning"
                        >{{ value3.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <!-- 索引列 -->
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                @click="editRoles(scope.row.id)"
                icon="el-icon-edit"
                size="mini"
                >编辑</el-button
              >

              <!-- 删除按钮 -->
              <el-tooltip
                effect="dark"
                content="删除"
                placement="top-start"
                :enterable="false"
              >
                <el-button
                  type="danger"
                  @click="deleteRoles(scope.row.id)"
                  icon="el-icon-delete"
                  circle
                ></el-button>
              </el-tooltip>

              <!-- 分配角色   enterable	鼠标是否可进入到 tooltip 中 -->
              <el-tooltip
                effect="dark"
                content="分配权限"
                placement="top-start"
                :enterable="false"
              >
                <el-button
                  @click="setRightsList(scope.row)"
                  type="warning"
                  icon="el-icon-setting"
                  circle
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      @close="dialogClose"
      :visible.sync="addDialogVisible"
      width="30%"
    >
      <el-form
        :model="addForm"
        ref="addFormRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      @close="editDialogClose"
      :visible.sync="editDialogVisible"
      width="30%"
    >
      <el-form
        :model="editForm"
        ref="editFormRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      @close="rightsDialogClose"
      :visible.sync="setRightsDialogVisible"
      width="50%"
    >
      <el-tree
        ref="treeRef"
        :data="rightsList"
        show-checkbox
        node-key="id"
        :default-checked-keys="defKeys"
        :props="treeProps"
        default-expand-all
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //所有角色
      rolesList: [],
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 要编辑的用户信息
      editForm: {},
      //所有权限
      rightsList: [],
      //控制添加角色对话框是否显示
      addDialogVisible: false,
      //控制编辑角色对话框是否显示
      editDialogVisible: false,
      //控制分配权限对话框是否显示
      setRightsDialogVisible: false,
      //树形控件的属性绑定
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      roleId: '' //即将分配权限的角色id
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: response } = await this.$axios.get('roles')
      if (response.meta.status !== 200)
        return this.$message.error('获取角色列表失败')
      this.rolesList = response.data
      //   console.log(response.data)
      return this.$message.success(response.meta.msg)
    },
    //添加角色
    async addRoles() {
      const { data: response } = await this.$axios.post('/roles', this.addForm)
      if (response.meta.status !== 201)
        return this.$message.error('添加角色失败')
      this.$message.success('添加角色成功')
      this.addDialogVisible = false //隐藏对话框
      this.getRolesList() //重新获取用户列表
    },
    //监听添加角色对话框关闭的事件
    dialogClose() {
      this.$refs.addFormRef.resetFields()
      //需要有prop属性 否则失效
      // console.log(this)
    },
    //监听编辑角色对话框关闭的事件
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 显示编辑角色对话框并显示信息
    async editRoles(id) {
      this.editDialogVisible = true
      const { data: response } = await this.$axios.get('roles/' + id)
      // console.log(response)
      if (response.meta.status !== 200)
        return this.$message.error('查询角色信息失败')
      this.$message.success('查询角色信息成功')
      this.editForm = response.data
    },
    //编辑角色
    async updateRoles() {
      const { data: response } = await this.$axios.put(
        'roles/' + this.editForm.roleId,
        { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc }
      )
      if (response.meta.status !== 200)
        return this.$message.error('修改角色信息失败')
      // 隐藏对话框
      this.editDialogVisible = false
      this.getRolesList()
      this.$message.success('修改角色信息成功')
    },
    //删除角色
    async deleteRoles(id) {
      await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: response } = await this.$axios.delete('roles/' + id)
          if (response.meta.status !== 200)
            return this.$message.error('删除角色失败')

          this.getRolesList()

          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除权限
    async deleteRights(role, rightId) {
      await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: response } = await this.$axios.delete(
            'roles/' + role.id + '/rights/' + rightId
          )
          if (response.meta.status !== 200)
            return this.$message.error('删除权限失败')
          //不建议刷新页面 这样会合起来
          //   this.getRolesList()
          role.children = response.data
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //分配权限功能
    async setRightsList(role) {
      this.roleId = role.id
      const { data: response } = await this.$axios.get('rights/tree')
      if (response.meta.status !== 200)
        return this.$message.error('获取权限列表失败')

      this.rightsList = response.data
      //   console.log(response.data)

      this.getLeafKeys(role, this.defKeys)
      this.setRightsDialogVisible = true
      return this.$message.success(response.meta.msg)
    },
    // 通过递归的形式获取到角色下三级权限的id
    getLeafKeys(node, arr) {
      //如果当前node节点不包含children 说明是三级节点
      if (!node.children) {
        //   将id保存到数组中
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    //监听添加分配权限对话框关闭的事件
    rightsDialogClose() {
      this.defKeys = []
      // console.log(this)
    },
    //储存为角色分配的权限信息
    async addRights() {
      // getCheckedKeys  返回目前被选中的节点的 key 所组成的数组
      // /getHalfCheckedKeys 返回目前半选中的节点的 key 所组成的数组
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keyStr = keys.join(',')
      const { data: response } = await this.$axios.post(
        'roles/' + this.roleId + '/rights',
        {
          rids: keyStr
        }
      )
      if (response.meta.status !== 200)
        return this.$message.error('更新权限列表失败')
      this.setRightsDialogVisible = false
      this.getRolesList()
      return this.$message.success('更新权限列表成功')
    }
  }
}
</script>

<style lang="less" scoped>
.addbtn {
  float: left;
  margin-bottom: 20px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 10px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
